package com.xiaoyu.lanling.net;

import android.os.Build;
import android.text.TextUtils;

import androidx.annotation.NonNull;

import com.alibaba.sdk.android.httpdns.HttpDns;
import com.alibaba.sdk.android.httpdns.HttpDnsService;
import com.xiaoyu.base.AppConfig;
import com.xiaoyu.base.app.AppContext;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import in.srain.cube.util.CLog;
import in.srain.cube.util.Env;
import okhttp3.Dns;

public class OkHttpDns implements Dns {

    private static final Dns DNS_SYSTEM = SYSTEM;

    private final HttpDnsService httpDnsService;
    private ArrayList<String> hostList = new ArrayList<>(Arrays.asList("api.nuan.chat", "newsns.yizhoucp.cn", "res-cdn.myrightone.com"));

    public OkHttpDns() {
        httpDnsService = HttpDns.getService(AppContext.getContext(), AppConfig.aliyunHttpDnsAccountId());
        httpDnsService.setHTTPSRequestEnabled(true);
        httpDnsService.setPreResolveAfterNetworkChanged(true);
        httpDnsService.setLogEnabled(Env.isDevOrInDevMode());
        httpDnsService.setDegradationFilter(s -> detectIfProxyExist());
        httpDnsService.setPreResolveHosts(hostList);
    }

    @Override
    public List<InetAddress> lookup(@NonNull String hostname) throws UnknownHostException {
        if (httpDnsService != null) {
            String ip = httpDnsService.getIpByHostAsync(hostname);
            CLog.d("HttpDns", "host: %s, dns ip: %s", hostname + "", ip + "");
            if (!TextUtils.isEmpty(ip)) {
                return Arrays.asList(InetAddress.getAllByName(ip));
            }
        }
        return DNS_SYSTEM.lookup(hostname);
    }

    private static boolean detectIfProxyExist() {
        final String proxyHost = System.getProperty("http.proxyHost");
        final String proxyPort = System.getProperty("http.proxyPort");
        final int port = Integer.parseInt(proxyPort != null ? proxyPort : "-1");
        return proxyHost != null && port != -1;
    }
}
